//base64转file对象代码
function dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while(n--){
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
}

//将base64转换为blob
function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while(n--){
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}

//将blob转换为file
function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

// 压缩图片
function compressedImg(img, quality = .7) {
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    let width = img.width
    let height = img.height
    canvas.width = width
    canvas.height = height
    // 铺底色
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(img, 0, 0, width, height)

    // 进行最小压缩
    let ndata = canvas.toDataURL('image/jpeg', quality)
    // console.log("*******压缩后的图片大小*******")
    // console.log(ndata)
    // console.log(ndata.length)
    return ndata
}

export {
    dataURLtoFile,
    dataURLtoBlob,
    blobToFile,
    compressedImg
}
